import re
import time
import hashlib
import datetime

class Auth:
    def __init__(self):
        self.uri = "rtmp://vt.qy-cloud.cn/uds/live"            # original uri
        self.key = "3QMIHtEss75koZM2"                         # private key of     authorization
        self.exp = int(time.time()) + 10 * 3600                   # expiration     time: 1 hour after current itme

    def getPushUrl(self):
        return self.a_auth(self.uri,self.key,self.exp)
    def md5sum(self,src):
        m = hashlib.md5()
        m.update(src)
        return m.hexdigest()
    def a_auth(self,uri, key, exp):
        p = re.compile("^(rtmp://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
        if not p:
            return None
        m = p.match(uri)
        scheme, host, path, args = m.groups()
        if not scheme: scheme = "rtmp://"
        if not path: path = "/"
        if not args: args = ""
        rand = "0"      # "0" by default, other value is ok
        uid = "0"       # "0" by default, other value is ok
        sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
        hashvalue = self.md5sum(sstring.encode('utf-8'))
        auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
        if args:
            return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
        else:
            return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)

if __name__ == "__main__":
    auth = Auth()
    url = auth.getPushUrl()
    print(url)